package com.elegantmall.service;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.jwt.JWT;
import com.elegantmall.dao.UserDao;
import com.elegantmall.pojo.UserContactPojo;
import com.elegantmall.pojo.UserPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl {
    @Autowired
    UserDao userDao;
    public Boolean login(String username,String password){
        UserPojo userPojo = userDao.selectById(username);
        if(userPojo == null){
            return false;
        }
        else if(!userPojo.getPassword().equals(password)){
            return false;
        }
        else{

            return true;
        }
    }
    public SaResult register(String username,String password,String nickname){
        UserPojo userPojo = userDao.selectById(username);
        if(userPojo !=null){
            return SaResult.error("用户名已被注册");
        }
        else{
            UserPojo userPojo2 = new UserPojo(username,password,nickname);
            userDao.insert(userPojo2);
            // 插入用户联系信息到 user_contact 表，address 和 telephone 初始化为空
            UserContactPojo userContactPojo = new UserContactPojo(username, "", "");
            userDao.insertUserContact(userContactPojo);
            return SaResult.ok("注册成功");


        }
    }
    public SaResult updateUser(String username, String newPassword, String newNickname) {
        UserPojo userPojo = userDao.selectById(username);
        if (userPojo == null) {
            return SaResult.error("用户不存在");
        } else {
            userPojo.setPassword(newPassword);
            userPojo.setNickName(newNickname);
            userDao.updateById(userPojo);
            return SaResult.ok("更新成功");
        }
    }
    public SaResult updateUserContact(String username, String address, String telephone) {
        int result = userDao.updateUserContact(username, address, telephone);
        if (result > 0) {
            return SaResult.ok("联系信息更新成功");
        } else {
            return SaResult.error("用户不存在或更新失败");
        }
    }
    public SaResult getUserContact(String username) {
    UserContactPojo userContactPojo = userDao.getUserContactByUsername(username);
    if (userContactPojo == null) {
        return SaResult.error("用户不存在或未设置联系信息");
    } else {
        return SaResult.ok().setData(userContactPojo);
    }
}




}
